package cn.edu.lcu.cs.javateaching.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 编写一个程序，分别使用字节流与字符流拷贝一个文本文件。要求如下：
 * 
 * a) 使用FileInputStream、FileOutputStream和FileReader、FileWriter分别进行拷贝。
 * 
 * b) 使用字节流拷贝时，定义一个1024字节的数组作为缓冲区。
 * 
 * c) 使用字符流拷贝时，使用BufferedReader和BufferedWriter包装流进行包装。
 * 
 * 
 * @author Ling
 *
 */
public class FileCopyUtil {

	private static int BUFFER_LENGTH = 1024;

	public static void main(String[] args) {
		String from = "d:/temp/index.html";
		String to = "d:/temp/index.bak";
		copyFileWithByteStream(from, to);
		copyFileWithCharStream(from, to);
	}

	/**
	 * 用字节流拷贝文件
	 * 
	 * @param from
	 * @param to
	 */
	public static void copyFileWithByteStream(String from, String to) {
		try (FileInputStream ins = new FileInputStream(from); FileOutputStream outs = new FileOutputStream(to)) {
			byte[] buffer = new byte[BUFFER_LENGTH];
			int len;
			while ((len = ins.read(buffer)) != -1) {
				outs.write(buffer, 0, len);
			}
			System.out.println("文件拷贝成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 用字符流拷贝文件
	 * 
	 * @param from
	 * @param to
	 */
	public static void copyFileWithCharStream(String from, String to) {
		try (BufferedReader reader = new BufferedReader(new FileReader(from));
				BufferedWriter writer = new BufferedWriter(new FileWriter(to))) {
			String line;
			while ((line = reader.readLine()) != null) {
				writer.write(line);
				writer.newLine();
			}
			System.out.println("文件拷贝成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
